package com.aceitunaproject.clientconnectionmanager;

import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import com.aceitunaproject.clientinterface.AceitunaClientInterface;
import com.aceitunaproject.shared.map.MapTile;
import com.aceitunaproject.shared.message.concrete.MapAreaRefreshEvent;
import com.aceitunaproject.clientinterface.eventadapters.AceitunaConnectionEventsHandler;
import com.aceitunaproject.clientinterface.eventregistering.MapAreaRefreshHandler;

/**
 * @author Federico Bergstein
 * 
 *  Holds an Aceituna Client Interface and properties to Identify it in a list and to determine if it should expire.
 * 
 */
public class ClientInterfaceHolder implements MapAreaRefreshHandler, AceitunaConnectionEventsHandler {

	private UUID id = UUID.randomUUID();
	private long lastRefreshTime = Calendar.getInstance().getTimeInMillis();
	private AceitunaClientInterface clientInterface;
    private List<MapTile> lastMap;
	private boolean isLoggedIn;
	private boolean hasReceivedMap;
	
	public ClientInterfaceHolder(ClientInterfaceFactory factory) {

		clientInterface = factory.getClientInterface();
		clientInterface.registerToEvent(this);
		clientInterface.registerForConnectionEvents(this);
	}

	/**
	 * @return the id
	 */
	public UUID getId() {
		return id;
	}

	/**
	 * @return the last time the connection was used.
	 */
	public long getLastRefreshTime() {
		return lastRefreshTime;
	}

	/**
	 * @return an Aceituna Client Interface to use as a client connection to the aceituna server
	 */
	public AceitunaClientInterface getClientInterface() {
		lastRefreshTime = Calendar.getInstance().getTimeInMillis();
		return clientInterface;
	}

	
	/**
	 * sets the client interface to null (not sure it's necessary, check)
	 */
	public void destroyClientInterface() {
		clientInterface = null;
		
	}

	@Override
	public void MapAreaRefresh(MapAreaRefreshEvent message) {
		lastMap = message.getAreaTiles();
		hasReceivedMap = true;
		
	}

	public List<MapTile> getLastMap() {
		hasReceivedMap = false;
		return lastMap;
	}

	

	/**
	 * @return true if the client connection has reported that the user is loged in
	 */
	public boolean isLoggedIn() {
		return isLoggedIn;
	}

	@Override
	public void loggedIn() {
		isLoggedIn = true;
		
	}

	@Override
	public void loginFailed(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void reconnected() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void reconnecting() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void disconnected(boolean arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	public boolean hasReceivedMap() {
		
		return hasReceivedMap;
	}

}
